<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseAdminController;
use App\Lib\Enum\ValRule;
use App\Lib\Logger;
use App\Lib\Validates;
use App\Models\QuestionVersion;
use App\Rules\CheckRule;
use App\Service\CategoryService;
use App\Service\CategoryVersionService;
use App\Service\QuestionService;
use App\Service\TagService;
use Illuminate\Http\Request;

class CategoryController extends BaseAdminController
{
    protected $categoryservice = "";
    protected $categoryversionservice = "";
    public function _init() {
        $this->categoryservice = new CategoryService();
        $this->categoryversionservice = new CategoryVersionService();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($groupId) {
        $check = Validates::isPositiveInteger($groupId);
        if (!$check) {
            return $this->tempNotice("admin.index", "浏览分类不存在", "error");
        }
        //获取分组内容
        $group = $this->categoryservice->getCategoryGroupList();
        //获取栏目内容
        $data = $this->categoryservice->getCategoryList2($groupId);
        return view('admin.category.index', ["error" => empty($data) ? 70000 : 0, "categories" => json_encode($data), "group" => $group, "groupId" => $groupId]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        if ($this->request->isMethod("get")) {
            $groupId = $this->request->get("groupId");
            $parent = $this->categoryservice->getCategoryById($this->request->get("parent_id"));
            if (empty($parent)) {
                $parent = ["id" => 0, "name" => "顶级","scope_course"=>1,"scope_exam"=>1];
            }
            //获取分组内容
            $group = $this->categoryservice->getCategoryGroupList();
            return view('admin.category.create', ["group" => $group, "groupId" => $groupId, "parent" => $parent,"course"=>$parent["scope_course"],"exam"=>$parent["scope_exam"]]);
        } else {
            return $this->store($this->request);
        }
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    protected function store() {
        $params = $this->categoryservice->getCData($this->request->all());
        if(array_key_exists("error",$params)&&$params["error"]>0){
            return $this->error($params["error"], $params["msg"]);
        }
        //插入
        $result = $this->categoryservice->addAndPath($params["data"]);
        if (!empty($result)) {
            return $this->success($result, "添加成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::CATEGORY, 'store', '添加失败', $params);
        return $this->error(70000, "添加失败");
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.category.index", "浏览分类不存在", "error");
        }
        $data = $this->categoryservice->getShowInfo($id);
        return view("admin.category.show", ["data" => $data]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit() {
        $check = Validates::isPositiveInteger($this->request->get("id"));
        if (!$check) {
            return $this->tempNotice("admin.index", "修改分类不存在", "error");
        }
        if ($this->request->isMethod("get")) {
            $data = $this->categoryservice->getCategoryById($this->request->get("id"));
            //获取分组内容
            $group = $this->categoryservice->getCategoryGroupList();
            //获取父级名称
            if ($data["parent_id"] == 0) {
                $father["id"] = 0;
                $father["name"] = "顶级";
                $father["scope_course"]=1;
                $father["scope_exam"]=1;
            } else {
                $father = $this->categoryservice->getCategoryById($data["parent_id"]);
            }
            return view("admin.category.edit", ["data" => $data, "group" => $group, "father" => $father]);
        } else {
            return $this->update($this->request->all());
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    protected function update($data) {
        $params = $this->categoryservice->getCData($data,1);
        if(array_key_exists("error",$params)&&$params["error"]>0){
            return $this->error($params["error"], $params["msg"]);
        }
        //更新
        $result = $this->categoryservice->update($params["data"]["id"], $params["data"]);
        if ($result) {
            $this->categoryservice->upDepth($params["data"]);
            return $this->success("", "更新成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::CATEGORY, 'update', '更新失败', $params);
        return $this->error(80000, "更新失败");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.category.index", "id必须是正整数", "error");
        }
        //删除前需验证课程、考试等信息是否在分类下面
        $exitQ = (new QuestionService())->first(["category_id"=>$id]);
        $exitC = $this->categoryservice->first(["parent_id"=>$id]);
        if(empty($exit)&&empty($exitC)){
            //删除
            $result = $this->categoryservice->delete($id);
            if (!$result) {
                $this->log(Logger::LOG_LEVEL_ERROR, Logger::ROLE, 'destroy', '系统角色不可删除，或删除失败', ['del_id' => $id]);
                return $this->error(80001, "系统角色不可删除");
            }
            $this->log(Logger::LOG_LEVEL_INFO, Logger::ROLE, 'destroy', '删除成功', ['del_id' => $id]);
            return $this->layuiDataSuccess("", 0, "删除成功");
        }
        return $this->layuiDataError(80002, "科目下含有试题或子科目，不可删除");

    }

    /**
     * 设置标签
     */
    public function settag($id) {
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice('admin.category.index', "浏览分类不存在", "error");
        }
        if($this->request->isMethod("get")){
            //获取分类信息
            $info = $this->categoryservice->getCategoryById($id);
            //获取标签组
            $tags = (new TagService())->tagGroupSelect($info);
            $examNum = empty($info["exam_tag_group"])?"":$info["exam_tag_group"][0]["id"];
            return view("admin.category.settag", ["info" => $info, "tags" => json_encode($tags),"examNum"=>$examNum]);
        }else{
            return $this->setTagStroe($id);
        }

    }

    protected function setTagStroe($category_id) {
        $params = $this->request->all();
        /*//参数验证
        $params = (new CheckRule($params["data"], ValRule::CATEGORY_TAG, ValRule::CATEGORY_TAG_MSG))->check();
        if ($params["error"] > 0) {
            return $this->error($params['error'], $params['msg']);
        }*/
        //添加
        $result = $this->categoryservice->addTags($category_id, $params["data"]);
        if ($result >= 0) {
            $this->log(Logger::LOG_LEVEL_INFO, Logger::CATEGORY, 'setTagStroe', "分类[ID:{$category_id}]的标签添加,成功", $result);
            return $this->success("", "标签添加成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::CATEGORY, 'setTagStroe', "分类[ID:{$category_id}]的标签添加,失败", $result);
        return $this->error(80000, "标签添加失败");
    }

    /**
     * 排序
     */
    public function setSort($id,$sort){
        //验证
        $params = (new CheckRule(["id"=>$id,"sort"=>$sort], ValRule::SORT, ValRule::SORT_MSG))->check();
        if ($params["error"] > 0) {
            return $this->error($params['error'], $params['msg']);
        }
        //排序
        $result = $this->categoryservice->setSort($id,$sort);
        if ($result) {
            $this->log(Logger::LOG_LEVEL_INFO, Logger::CATEGORY, 'setSort', "分类[ID:{$id}]更新排序,成功", "");
            return $this->success("", "排序更新成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::CATEGORY, 'setSort', "分类[ID:{$id}]更新排序,失败", "");
        return $this->error(80000, "排序更新失败");
    }


    /**设置版本页面*/
    public function setVersion($id){
        $this->validateData(["id"=>$id]);
        if($this->request->isMethod("get")){
            //分类信息
            $info = $this->categoryservice->first(["id"=>$id]);
            //版本信息
            $versions=getData("QuestionVersionDataTag");
            return view("admin.category.assign_version",["info"=>$info,"versions"=>$versions]);
        }else{
            $data = $this->request->all();
            $this->validateData(array_key_exists("data",$data)?$data["data"]:[],"setVersionID");
            return $this->setVersionSort($id,$data["data"]);
        }
    }

    /**设置版本入库*/
    protected function setVersionSort($id,$data){
        $result = $this->categoryversionservice->insertAndUpdate($id,$data);
        if($result["error"]>0){
            $this->log(Logger::LOG_LEVEL_ERROR,"CategoryVersion","setVersionSort",$result["msg"],$data);
            return $this->tempLaravelError("admin.category.update.attach.1","添加/更新失败",["id"=>$id]);
        }
        $this->log(Logger::LOG_LEVEL_INFO,"CategoryVersion","setVersionSort",$result["msg"],$data);
        return $this->tempLaravelError("admin.category.update.attach.1","添加/更新成功",["id"=>$id],"success");
    }

}
